<?php


namespace app\services\goods;




use app\services\BaseService;
use think\facade\Db;

use app\models\goods\GoodsModel;
use app\models\goods\GoodsSkuModel;

class GoodsService extends BaseService
{

    protected static function initModel()
    {
        return new GoodsModel();
    }

    /**
     * 修改商品库存
     * @return void
     */
    public static function setStock($sku_id,$amount = 0,$type = 1)
    {
        try {
            $skuInfo = GoodsSkuModel::find($sku_id);
            if (!$skuInfo) {
                return true;
            }
            $before = $skuInfo['stock'];
            if ($type < 100) {
                //库存增加
                $after = $before + $amount;
                $skuInfo->stock = $skuInfo->stock + $amount;
            } else {
                //库存减少
                if ($before < $amount) {
                    throw new \Exception('商品库存不足');
                }
                $after = $before - $amount;
            }
            $skuInfo->stock = $after;
            $skuInfo->save();

            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }

    }

}